<template>
	<view>
		<u-navbar title="修改密码">
		</u-navbar>
		<view class="u-p-20">
			<u-form :model="form" ref="uForm" :label-width="150" :error-type="errorType">
				<u-form-item  label="旧密码" prop="oldPassword">
					<u-input type="password" v-model="form.oldPassword"/>
				</u-form-item>
				<u-form-item label="新密码" prop="newPassword">
					<u-input type="password" v-model="form.newPassword"/>
				</u-form-item>
				<u-form-item label="确认密码" prop="password">
					<u-input type="password" v-model="form.password"/>
				</u-form-item>
			</u-form>
		</view>
		<view class="u-m-20">
			<u-button type="primary" @click="submit">提交</u-button>
		</view>
	</view>
</template>

<script>
import {decrypt, encrypt} from "../../utils/jsencrypt";

export default {
	name: "updatePwd",
	data() {
		return {
			errorType: ['message'],
			form: {
				oldPassword: '',
				newPassword: '',
				password: ''
			},
			rules: {
				oldPassword: [
					{
						required: true,
						message: '请输入旧密码',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					}
				],
				newPassword: [
					{
						required: true,
						message: '请输入新密码',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					},
					{
						validator: (rule, value, callback) => {
							return value == this.form.password;
						},
						message: '密码和确认密码输入不一致'
					}
				],
				password: [
					{
						required: true,
						message: '请输入确认密码',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					},
					{
						validator: (rule, value, callback) => {
							console.log(value)
							console.log(this.form.newPassword)
							return value == this.form.newPassword;
						},
						message: '密码和确认密码输入不一致'
					},
				]
			}
		};
	},
	onLoad() {
	},
	// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	methods: {
		submit() {
			this.$refs.uForm.validate(valid => {
				if (valid) {
					this.$u.api.updatePassword({
						oldPassword: encrypt(this.form.oldPassword),
						newPassword: encrypt(this.form.newPassword)
					}).then(res => {
						this.$u.toast('保存成功');
					})
				} else {
					console.log('验证失败');
				}
			});
		}
	}
}
</script>

